
package vv.lines.view.swing.animation;

import vv.lines.core.Ball;
import vv.lines.core.animations.AbstractAnimation;
import vv.lines.core.animations.AnimationType;
import vv.lines.view.BallView;

import java.awt.*;
import java.util.Collection;

import static vv.lines.view.swing.utils.SwingLinesConstants.MAX_KEY;
import static vv.lines.view.swing.utils.SwingLinesConstants.MIN_KEY;

/**
 *
 * @author vpotapenko
 */
public class SwingActiveAnimation extends AbstractAnimation {

    private Rectangle viewRect;
    private Rectangle transformRect;

    private int k = 0;
    private boolean up = false;

    public SwingActiveAnimation() {
        transformRect = new Rectangle();
        viewRect = new Rectangle();
    }

    protected void updateAnimationState() {
        k = up ? k + 1 : k - 1;
        checkDirection();
    }

    private void checkDirection() {
        if (k >= MAX_KEY) up = false;
        if (k <= MIN_KEY) up = true;
    }

    public boolean hasAnimation() {
        return true;
    }

    private void setTransformRectOnView(BallView view) {
        view.setLocation(transformRect.x, transformRect.y);
        view.setSize(transformRect.width, transformRect.height);
    }

    private void updateBallView(Ball ball) {
        updateViewRect(ball);
        updateTransformRect();
        setTransformRectOnView(ball.getView());
    }

    private void updateTransformRect() {
        transformRect.setBounds(viewRect.x - k / 2, viewRect.y + k,
                viewRect.width + k, viewRect.height - k);
    }

    private void updateViewRect(Ball ball) {
        viewRect.setBounds(ball.getX(), ball.getY(), ball.getWidth(), ball.getHeight());
    }

    protected void updateView() {
        Collection<Ball> target = getTarget();
        for (Ball ball : target) {
            updateBallView(ball);
        }
    }

    public AnimationType getType() {
        return AnimationType.ACTIVE;
    }
}
